package com.example.smartcitydemo.ext

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import com.example.smartcity_jscs.network.ResultStates.Resource
import com.example.smartcitydemo.exception.AppExcpetion
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect

/**
 * @PACKAGE_NAME: com.example.smartcitydemo.ext
 * @NAME: Caleb.F
 * @DATE: 2021/11/4 16:24
 * @Email: 1919796283@qq.com
 */
fun <T> ViewModel.getLiveData(
    rawData: suspend () -> Flow<Resource<T>>
): LiveData<Resource<T>> {
    return liveData(Dispatchers.IO) {
        emit(Resource.Loading<T>())
        try {
            rawData().collect {
                emit(it)
            }
        } catch (e: Throwable) {
            val transFormException = AppExcpetion.transFormException(e)
            AppExcpetion.handleException(transFormException)
            emit(Resource.Failure<T>(transFormException.errorMsg,transFormException))
        }
    }
}